package com.intellagric.service.sso.impl.module;

import com.intellagric.common.jedis.JedisClient;
import com.intellagric.common.pojo.ResponseMessage;
import com.intellagric.common.utils.JsonUtils;
import com.intellagric.pojo.SysUser;
import com.intellagric.service.sso.TokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @Auther: zhy
 * @Date: 2018/10/7
 * @Description: token相关服务实现
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private JedisClient jedisClient;

    @Value("${SESSION_EXPIRE}")
    private Integer SESSION_EXPIRE;

    @Override
    public ResponseMessage getUserByToken(String token) {
        //根据token查询用户信息
        String user = jedisClient.get("SESSION:" + token);
        //若取不到表示过期
        if (StringUtils.isBlank(user)) {
            return ResponseMessage.fail("用户登录已过期");
        }
        //重置过期时间
        jedisClient.expire("SESSION:" + token,SESSION_EXPIRE);
        return ResponseMessage.success().add("user",JsonUtils.jsonToPojo(user, SysUser.class));
    }

    @Override
    public ResponseMessage editUserByToken(String token,SysUser sysUser) {
        jedisClient.set("SESSION:" + token,JsonUtils.objectToJson(sysUser));
        //重置过期时间
        jedisClient.expire("SESSION:" + token,SESSION_EXPIRE);
        return ResponseMessage.success().add("user",sysUser);
    }


}
